<template>
  <el-card>
    <div class="chart-container" ref="chartRef"></div>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "PieChart",
};
</script>

<script lang="ts" setup>
import { ref, onMounted } from "vue";
import * as echarts from "echarts";

const chartRef = ref();
onMounted(() => {
  const myEcharts = echarts.init(chartRef.value);

  const data = [
    {
      name: "粉面粥店",
      value: 56,
    },
    {
      name: "简餐便当",
      value: 33,
    },
    {
      name: "汉堡披萨",
      value: 44,
    },
    {
      name: "香锅冒菜",
      value: 66,
    },
    {
      name: "小吃炸串",
      value: 50,
    },
    {
      name: "地方菜系",
      value: 11,
    },
    {
      name: "轻食简餐",
      value: 46,
    },
  ];

  const total = data.reduce((p, c) => {
    return p + c.value;
  }, 0);

  const option = {
    title: [
      {
        text: "品类分布",
      },
      {
        text: "累计订单量",
        subtext: 406,
        left: "center",
        top: "42%",
        textStyle: {
          color: "gray",
          fontSize: 14,
        },
        subtextStyle: {
          fontSize: 25,
          fontWeight: 500,
          color: "#000",
        },
      },
    ],
    series: {
      type: "pie",
      data,
      radius: ["50%", "70%"],
      itemStyle: {
        borderWidth: 2,
        borderColor: "#fff",
      },
    },
    tooltip: {
      formatter(params: any) {
        return `品类分布 <br/>
        ${params.marker}${params.name} <br/>
        ${params.marker}数量:${params.value} <br/>
        ${params.marker}占比:${params.percent}%`;
      },
    },
    legend: {
      right: 0,
      top: "middle",
      orient: "vertical",
      formatter(name: string) {
        const item = data.find((item) => item.name === name) as {
          name: string;
          value: number;
        };
        const percent = ((item.value / total) * 100).toFixed(2);
        return `${name} | ${percent}%`;
      },
    },
  };
  myEcharts.setOption(option);
});
</script>

<style scoped>
.chart-container {
  width: 500px;
  height: 300px;
}
</style>
